import { Component, OnInit } from '@angular/core';
import { StoreService } from '../store.service';
import {
  Condition,
  ConditionGroup,
  Query,
  QueryPackage,
  ShowCondition,
} from '../classes';
import { DataService } from '../data.service';
import notify from 'devextreme/ui/notify';
import fileSaver from 'file-saver';
import { NgxEchartsModule } from 'ngx-echarts';
import { EChartOption } from 'echarts';
@Component({
  selector: 'app-advancedquery',
  templateUrl: './advancedquery.component.html',
  styleUrls: ['./advancedquery.component.less'],
})
export class AdvancedqueryComponent implements OnInit {
  constructor(public storeService: StoreService, public ds: DataService) {
    this.showconditionlist = false;
  }
  popupVisible: boolean = false;
  modelVisible: boolean = false;
  autoAddShwoColumn: boolean = true;
  showQueryResult: boolean = true;
  results: any[] = [];
  showColumns: ShowCondition[];
  editShowColumn() {}
  showModel() {
    this.modelVisible = true;
  }
  package = new QueryPackage();
  async saveModel() {
    //this.package = new QueryPackage();
    this.storeService.query.name = this.package.name;
    this.package.version = this.storeService.query.version;
    this.ds.setQueryObject(this.storeService.query, this.package, 'query');
    await this.ds.setModel(this.package);
    this.modelVisible = false;
  }
  cancelModel() {
    this.modelVisible = false;
  }
  ngOnInit() {
    //console.log(this.showconditionlist);
  }
  source: string = '';
  target: string = '';
  showconditionlist: boolean = false;
  settings: boolean = false;
  //conditionlist: Condition[] = [];
  clickAddConditionButton: boolean = false;
  // private addcondition() {
  //   this.showconditionlist = true;
  // }
  select(item) {
    let c = new Condition();
    let cg = new ConditionGroup();
    cg.conditions.push(c);
    //console.log(item);
    c.Target = item;
    this.storeService.query.conditionpipe.push(cg);
    this.showconditionlist = false;
  }

  async query() {
    console.log('query start');
    console.log(this.storeService.query.conditionpipe);
    let r = await this.ds.search(
      'mr',
      this.storeService.query,
      [],
      1,
      100000000
    );
    //console.log(ro);
    //console.log(ro.body);
    let ro = JSON.parse(r as string);
    // console.log(ro['body']);
    // console.log(ro['body']['results']);
    // console.log(ro['body']['columns']);
    this.storeService.tableresults = ro['body']['results'];
    this.storeService.resultObjectProperties = ro['body']['columns'];
    this.mappingcolumn();
    this.source = undefined;
    this.target = undefined;
    if (this.showQueryResult) this.results = this.storeService.tableresults;
    // console.log(this.storeService.tableresults);
    // if (
    //   this.storeService.tableresults !== undefined &&
    //   this.storeService.tableresults.length > 0
    // ) {
    //   this.storeService.tableresults.forEach(v => {
    //     Object.keys(v).forEach(c => {
    //       if (!this.storeService.resultObjectProperties.includes(c))
    //         this.storeService.resultObjectProperties.push(c);
    //     });
    //   });
    // let element = this.storeService.tableresults[0];
    // console.log(element);
    // this.storeService.resultObjectProperties = Object.keys(element);
    //}
    //console.log(this.storeService.resultObjectProperties);
  }
  addconditiongroup() {
    let cg = new ConditionGroup();
    this.storeService.query.conditionpipe.push(cg);
  }
  export() {
    if (this.storeService.tableresults.length > 0) {
      let s = this.ds.getCsv(this.storeService.tableresults, this.mappingItems);

      let blob = new Blob([s], {
        type: 'text/plain;charset=utf-8',
      });
      fileSaver.saveAs(blob, this.storeService.query.name + '.query.csv');
    }
  }
  // remove(item) {
  //   var i = this.conditionlist.findIndex(v => v === item);
  //   if (i > -1) this.conditionlist.splice(i, 1);
  // }

  closeConditionList() {
    if (!this.clickAddConditionButton) this.showconditionlist = false;
  }
  removeGroup(item) {
    this.storeService.query.conditionpipe.splice(
      this.storeService.query.conditionpipe.indexOf(item),
      1
    );
  }
  createquery() {
    this.storeService.query = new Query();
    this.storeService.tableresults = [];
    this.storeService.resultObjectProperties = [];
    this.results = [];
  }

  savequery() {
    this.popupVisible = true;
  }
  confirm() {
    if (
      this.storeService.query.name === undefined ||
      this.storeService.query.name === ''
    ) {
      notify('未输入名称', 'error', 600);
    } else {
      let blob = new Blob([JSON.stringify(this.storeService.query)], {
        type: 'text/plain;charset=utf-8',
      });
      fileSaver.saveAs(blob, this.storeService.query.name + '.query.json');
    }
    this.popupVisible = false;
  }
  cancel() {
    this.popupVisible = false;
  }
  handleFileSelect(evt) {
    var files = evt.target.files;
    var f = files[0];
    var reader = new FileReader();

    reader.readAsText(f);
    reader.onload = ((f) => {
      return (e) => {
        let query = JSON.parse(e.target.result);
        this.storeService.query = this.ds.cloneQuery(query);
      };
    })(f);
  }

  mappingItems: string[] = [];
  public mappingcolumn() {
    if (this.storeService.tableresults.length == 0) return;

    this.mappingItems = [];
    for (let i = 0; i < this.storeService.tableresults.length; i++) {
      const o = this.storeService.tableresults[i];
      for (let index = 0; index < Object.keys(o).length; index++) {
        const element = Object.keys(o)[index];
        if (!this.mappingItems.includes(element))
          this.mappingItems.push(element);
      }
    }
  }

  chartOption;
  prepareData() {
    let link = [];
    let factor = [];
    for (
      let index = 0;
      index < this.storeService.tableresults.length;
      index++
    ) {
      const element = this.storeService.tableresults[index];

      let source = element[this.source];

      let target = element[this.target];
      if (source === undefined) source = 'undefined';
      if (source === null) source = 'null';
      if (target === undefined) target = 'undefined';
      if (target === null) target = 'null';
      source = this.source + ':' + source;
      target = this.target + ':' + target;
      if (factor.find((v) => v['name'] === source) === undefined)
        factor.push({ name: source });
      if (factor.find((v) => v['name'] === target) === undefined)
        factor.push({ name: target });
      let circle = link.find(
        (v) => v['source'] === target && v['target'] === source
      );
      if (circle === undefined) {
        let r = link.find(
          (v) => v['source'] === source && v['target'] === target
        );
        if (r === undefined)
          link.push({ source: source, target: target, value: 1 });
        else r['value']++;
      }
    }

    return [factor, link];
  }
  public mapping() {
    if (this.source === undefined || this.target === undefined) {
      alert('missing source or target,please select column to mapping!');
      return;
    }
    let rl = this.prepareData();
    // console.log(rl[0]);
    // console.log(rl[1]);
    this.chartOption = {
      series: {
        type: 'sankey',
        layout: 'none',
        focusNodeAdjacency: 'allEdges',
        data: rl[0],

        links: rl[1],
      },
    };
  }

  public hotspot() {}
}
